import { defineStore } from 'pinia'

// 商品状态管理
export const useProductStore = defineStore('product', {
  state: () => ({
    products: [], // 商品列表
    currentProduct: null, // 当前查看的商品详情
    categories: [], // 商品分类
    brands: [], // 品牌列表
    filters: {
      category: '',
      brand: '',
      priceRange: [0, 10000],
      sortBy: 'default'
    },
    pagination: {
      currentPage: 1,
      pageSize: 12,
      total: 0
    },
    isLoading: false
  }),
  getters: {
    // 获取筛选后的商品列表
    filteredProducts: (state) => {
      let result = [...state.products]
      
      // 按分类筛选
      if (state.filters.category) {
        result = result.filter(product => product.categoryId === state.filters.category)
      }
      
      // 按品牌筛选
      if (state.filters.brand) {
        result = result.filter(product => product.brandId === state.filters.brand)
      }
      
      // 按价格区间筛选
      result = result.filter(product => 
        product.price >= state.filters.priceRange[0] && 
        product.price <= state.filters.priceRange[1]
      )
      
      // 排序
      switch (state.filters.sortBy) {
        case 'price-asc':
          result.sort((a, b) => a.price - b.price)
          break
        case 'price-desc':
          result.sort((a, b) => b.price - a.price)
          break
        case 'sales':
          result.sort((a, b) => b.sales - a.sales)
          break
        case 'newest':
          result.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
          break
        default:
          // 默认排序
          break
      }
      
      return result
    },
    
    // 分页后的商品列表
    paginatedProducts: (state) => {
      const filtered = state.filteredProducts
      const start = (state.pagination.currentPage - 1) * state.pagination.pageSize
      const end = start + state.pagination.pageSize
      return filtered.slice(start, end)
    }
  },
  actions: {
    // 设置商品列表
    setProducts(products) {
      this.products = products
      this.pagination.total = products.length
    },
    
    // 设置当前商品
    setCurrentProduct(product) {
      this.currentProduct = product
    },
    
    // 设置分类列表
    setCategories(categories) {
      this.categories = categories
    },
    
    // 设置品牌列表
    setBrands(brands) {
      this.brands = brands
    },
    
    // 更新筛选条件
    updateFilters(filters) {
      this.filters = {
        ...this.filters,
        ...filters
      }
      this.pagination.currentPage = 1
    },
    
    // 重置筛选条件
    resetFilters() {
      this.filters = {
        category: '',
        brand: '',
        priceRange: [0, 10000],
        sortBy: 'default'
      }
      this.pagination.currentPage = 1
    },
    
    // 设置分页信息
    setPagination(pagination) {
      this.pagination = {
        ...this.pagination,
        ...pagination
      }
    },
    
    // 加载商品列表（模拟）
    async loadProducts(page = 1, pageSize = 12) {
      try {
        this.isLoading = true
        // 这里应该调用后端API获取商品列表
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        // 模拟商品数据
        const mockProducts = Array.from({ length: 24 }, (_, index) => ({
          id: `PROD${Date.now()}${index}`,
          name: `商品名称 ${index + 1}`,
          description: `这是商品${index + 1}的详细描述，包含了商品的特性、规格、用途等信息。用户可以通过这些信息了解商品的具体情况，以便做出购买决策。`,
          price: Math.floor(Math.random() * 9000) + 1000,
          originalPrice: Math.floor(Math.random() * 10000) + 1000,
          image: `https://picsum.photos/id/${index + 20}/400/300`,
          images: [
            `https://picsum.photos/id/${index + 20}/800/600`,
            `https://picsum.photos/id/${index + 30}/800/600`,
            `https://picsum.photos/id/${index + 40}/800/600`
          ],
          categoryId: `CAT${Math.floor(index / 6) + 1}`,
          categoryName: `分类${Math.floor(index / 6) + 1}`,
          brandId: `BRAND${(index % 3) + 1}`,
          brandName: `品牌${(index % 3) + 1}`,
          sales: Math.floor(Math.random() * 10000),
          stock: Math.floor(Math.random() * 1000) + 100,
          status: 1,
          attributes: {
            color: ['红色', '蓝色', '黑色'],
            size: ['S', 'M', 'L', 'XL']
          },
          createTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString()
        }))
        
        this.setProducts(mockProducts)
        this.setPagination({ currentPage: page, pageSize })
        this.isLoading = false
        return { success: true, products: mockProducts }
      } catch (error) {
        console.error('加载商品列表失败:', error)
        this.isLoading = false
        return { success: false, message: '加载商品列表失败，请重试' }
      }
    },
    
    // 根据ID获取商品详情（模拟）
    async getProductById(id) {
      try {
        this.isLoading = true
        // 这里应该调用后端API获取商品详情
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 800))
        
        // 模拟商品详情数据
        const mockProduct = {
          id,
          name: '精选高品质智能手表',
          description: `这是一款高品质智能手表，具有多种功能：\n\n1. 健康监测：心率、血氧、睡眠监测\n2. 运动追踪：支持多种运动模式\n3. 智能提醒：来电、短信、应用通知\n4. 长续航：一次充电可达7天\n5. 防水设计：50米防水\n6. 支付功能：支持多种支付方式\n\n产品采用优质材料制作，外观时尚，佩戴舒适，是您日常生活的得力助手。`,
          price: 1299,
          originalPrice: 1599,
          image: 'https://picsum.photos/id/96/400/300',
          images: [
            'https://picsum.photos/id/96/800/600',
            'https://picsum.photos/id/26/800/600',
            'https://picsum.photos/id/160/800/600',
            'https://picsum.photos/id/201/800/600'
          ],
          categoryId: 'CAT1',
          categoryName: '智能设备',
          brandId: 'BRAND1',
          brandName: '科技先锋',
          sales: 3256,
          stock: 128,
          status: 1,
          attributes: {
            color: ['黑色', '银色', '玫瑰金'],
            size: ['42mm', '46mm']
          },
          specifications: [
            { name: '屏幕尺寸', value: '1.78英寸' },
            { name: '分辨率', value: '368 x 448像素' },
            { name: '处理器', value: '双核处理器' },
            { name: '内存', value: '1GB RAM + 32GB ROM' },
            { name: '电池容量', value: '420mAh' },
            { name: '充电方式', value: '磁吸充电' },
            { name: '连接方式', value: '蓝牙5.0, Wi-Fi' },
            { name: '防水等级', value: '5ATM' }
          ],
          createTime: '2023-06-15T10:30:00Z',
          ratings: {
            average: 4.8,
            count: 568,
            details: [
              { level: 5, count: 425 },
              { level: 4, count: 102 },
              { level: 3, count: 31 },
              { level: 2, count: 8 },
              { level: 1, count: 2 }
            ]
          },
          reviews: [
            {
              id: 'REV001',
              userId: 'USER001',
              userName: '张先生',
              userAvatar: 'https://picsum.photos/id/64/100/100',
              rating: 5,
              content: '手表非常好用，功能齐全，续航也不错，推荐购买！',
              createTime: '2023-06-20T15:20:00Z',
              images: [
                'https://picsum.photos/id/119/400/300'
              ]
            },
            {
              id: 'REV002',
              userId: 'USER002',
              userName: '李女士',
              userAvatar: 'https://picsum.photos/id/65/100/100',
              rating: 4,
              content: '外观很漂亮，功能也很实用，就是有时候反应有点慢。',
              createTime: '2023-06-18T09:45:00Z',
              images: []
            }
          ]
        }
        
        this.setCurrentProduct(mockProduct)
        this.isLoading = false
        return { success: true, product: mockProduct }
      } catch (error) {
        console.error('获取商品详情失败:', error)
        this.isLoading = false
        return { success: false, message: '获取商品详情失败，请重试' }
      }
    },
    
    // 获取商品分类列表（模拟）
    async loadCategories() {
      try {
        // 这里应该调用后端API获取分类列表
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 500))
        
        // 模拟分类数据
        const mockCategories = [
          { id: 'CAT1', name: '智能设备', parentId: '' },
          { id: 'CAT2', name: '家居生活', parentId: '' },
          { id: 'CAT3', name: '时尚服饰', parentId: '' },
          { id: 'CAT4', name: '美妆个护', parentId: '' }
        ]
        
        this.setCategories(mockCategories)
        return { success: true, categories: mockCategories }
      } catch (error) {
        console.error('加载分类失败:', error)
        return { success: false, message: '加载分类失败，请重试' }
      }
    },
    
    // 获取品牌列表（模拟）
    async loadBrands() {
      try {
        // 这里应该调用后端API获取品牌列表
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 500))
        
        // 模拟品牌数据
        const mockBrands = [
          { id: 'BRAND1', name: '科技先锋' },
          { id: 'BRAND2', name: '生活优品' },
          { id: 'BRAND3', name: '时尚前线' }
        ]
        
        this.setBrands(mockBrands)
        return { success: true, brands: mockBrands }
      } catch (error) {
        console.error('加载品牌失败:', error)
        return { success: false, message: '加载品牌失败，请重试' }
      }
    }
  }
})